package logs

import (
	"io/ioutil"
	"os"
	"sync"
	"time"
)

type Map struct {
	m       map[string]*Entity
	mu      sync.RWMutex
	saveDay int
}

func (this *Map) Add(e ...*Entity) *Map {
	this.mu.Lock()
	defer this.mu.Unlock()
	for _, v := range e {
		this.m[v.Key()] = v
	}
	return this
}

func (this *Map) Get(key string) *Entity {
	this.mu.RLock()
	val, ok := this.m[key]
	this.mu.RUnlock()
	if ok {
		return val
	}
	val = NewEntity(key).SetLevel(0)
	this.Add(val)
	return val
}

func newMap(interval time.Duration) *Map {
	data := &Map{
		m: make(map[string]*Entity),
	}
	go func() {
		time.Sleep(time.Minute)
		for {
			if data.saveDay > 0 {
				date := time.Now().AddDate(0, 0, -data.saveDay).Format("2006-01-02")
				files, _ := ioutil.ReadDir(defaultPath)
				for _, v := range files {
					if len(v.Name()) == 10 && v.Name() <= date {
						PrintErr(os.RemoveAll(defaultPath + "/" + v.Name()))
					}
				}
			}
			time.Sleep(interval)
		}
	}()
	return data
}
